import React, { useCallback, useState, useEffect, useRef } from 'react';
import { Toast } from 'antd-mobile';
import produce from 'immer';
import NavBarItem from '@/component/NavBarItem';
import CartItem from './components/CartItem';
import { fetchShopCarList, fetchChecked, fetchNum } from '@/services/shopcar';

import styles from './index.less';

const ShopCar = () => {
  const [cartList, setCartList] = useState<any[]>([]);
  const cartListRef=useRef<any[]>([])

  useEffect(() => {
    fetchShopCarList().then((res) => {
      setCartList(produce(res.data, draft => {
        draft[0].goods.stock = 4
        draft[1].goods.stock = 7
        draft[2].goods.stock = 10
      }));
    });
  }, []);

  const handleChangeCheck = useCallback(
    async (value, id) => {
      const arr = produce(cartList, (draft) => {
        const index = draft.findIndex((item) => item.id === id);
        draft[index].is_checked = value ? 1 : 0;
      });
      setCartList(arr);
      let checkedArr = arr
        .filter((el) => el.is_checked === 1)
        .map((item) => item.id);
      await fetchChecked(checkedArr);
    },
    [cartList],
  );

  const handleChangeNum = useCallback(
    async (num, id) => {
      // const index = cartList.findIndex(item => item.id === id);
      // const stock = cartList[index].goods.stock
      // if (stock >= num) {
      //   const narr = produce(cartList, draft => {
      //     draft[index].num = num
      //   })
      //   setCartList(narr)
      //   await fetchNum(id, num)
      // }else{
      //   Toast.show('库存不足')
      // }

      const arr = produce(cartListRef.current.length?cartListRef.current:cartList, (draft) => {
        const index = draft.findIndex((item) => item.id === id);
        draft[index].num = num;
      });
      cartListRef.current=arr
      setCartList(arr);
      // await fetchNum(id, num);
    },
    [cartList],
  );

  return (
    <>
      <NavBarItem title="购物车" />
      {cartList.map((item) => (
        <CartItem
          key={item.id}
          id={item.id}
          ImgSrc={item.goods.cover_url}
          checked={item.is_checked}
          price={item.goods.price}
          title={item.goods.title}
          num={item.num}
          max={item.goods.stock}
          onChangeCheck={handleChangeCheck}
          onChangeNum={handleChangeNum}
        />
      ))}
    </>
  );
};

export default ShopCar;
